package com.dingreading.cloud.soms.service.impl;

import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.*;
import com.dingreading.cloud.common.util.aliyun.MstCdnUtil;
import com.dingreading.cloud.soms.dto.MstXcxStudentHomeworkDto;
import com.dingreading.cloud.soms.entity.MstXcxStudentHomework;
import com.dingreading.cloud.soms.entity.Staff;
import com.dingreading.cloud.soms.entity.StaffRoles;
import com.dingreading.cloud.soms.entity.table.MstXcxStudentHomeworkTableDef;
import com.dingreading.cloud.soms.mapper.MstXcxStudentHomeworkMapper;
import com.dingreading.cloud.soms.service.CmservicesService;
import com.dingreading.cloud.soms.service.MstXcxStudentHomeworkService;
import com.dingreading.cloud.soms.util.DataProcessUtils;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.QueryWrapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.dingreading.cloud.soms.entity.table.MembersTableDef.members;

/**
 * 小程序学生课后作业表 服务层实现。
 *
 * @author EDY
 * @since 2025-11-03
 */
@Service
public class MstXcxStudentHomeworkServiceImpl extends BaseServiceImpl<MstXcxStudentHomeworkMapper, MstXcxStudentHomework, MstXcxStudentHomeworkTableDef> implements MstXcxStudentHomeworkService {

    @Override
    protected MstXcxStudentHomeworkTableDef getTable() {
        return MstXcxStudentHomeworkTableDef.mstXcxStudentHomework;
    }

    @Resource
    private CmservicesService cmservicesService;
    @Resource
    private DataProcessUtils dataProcessUtils;

    @Override
    public Page<MstXcxStudentHomeworkDto> pageList(
            PageUtil pageUtil, String corpUid, String storeUid, String staffUid, String staffName,
            String keyword, String subjectUid, String beginDate, String endDate, Staff staff,
            StaffRoles staffRole
    ) {
        QueryCondition condition = QueryCondition.createEmpty()
                .and(table.agencyUid.eq(corpUid))
                .and(table.storeUid.eq(storeUid));

        if (StringUtils.isNotBlank(subjectUid)) {
            condition.and(table.projectUid.eq(subjectUid));
        }
        if (StringUtils.isNotBlank(keyword))
            condition.and(members.memberName.like(keyword).or(members.mob.like(keyword)));

        if (StringUtils.isNotBlank(beginDate) && StringUtils.isNotBlank(endDate))
            condition.and(table.addTime.between(QueryFiledUtil.appendMin00(beginDate), QueryFiledUtil.appendMin24(endDate)));

        List<String> studentUids;
        if (!AccountUtil.isStoreManager(staffRole.getRoles())) {
            studentUids = cmservicesService.getStudentsByTeacher(corpUid, storeUid, staff.getUid());
            if (CollectionUtils.isEmpty(studentUids)) {
                condition.and(table.evaluationStaffUid.eq(staff.getUid()));
            }
            condition.and(table.studentUid.in(studentUids));
        }

        QueryWrapper wrapper = QueryWrapper.create()
                .leftJoin(members).on(table.studentUid.eq(members.uid))
                .where(condition)
                .orderBy(table.id.desc());

        Page<MstXcxStudentHomeworkDto> homeworkDtoPage = getMapper().paginateWithRelationsAs(
                Page.of(pageUtil.getPage(), pageUtil.getRows()), wrapper, MstXcxStudentHomeworkDto.class
        );
        return homeworkDtoPage;
    }

    @Override
    public R<Object> getBean(String corpUid, String storeUid, String staffUid, String staffName, String uid, String ip) {
        QueryCondition condition = QueryCondition.createEmpty()
                .and(table.agencyUid.eq(corpUid))
                .and(table.storeUid.eq(storeUid))
                .and(table.uid.eq(uid))
                .and(table.enabled.eq(1));
        QueryWrapper wrapper = QueryWrapper.create()
                .where(condition);
        MstXcxStudentHomeworkDto homework = getMapper().selectOneWithRelationsByQueryAs(wrapper, MstXcxStudentHomeworkDto.class);

        if (homework != null && CollectionUtils.isNotEmpty(homework.getHomeworkImageUrls())) {
            long expire = MstCdnUtil.getImgExpire();
            List<String> cdnImageUrls = homework.getHomeworkImageUrls().stream()
                    .map((String url) -> dataProcessUtils.getXcxUrl(url, ip, expire))
                    .collect(Collectors.toList());
            homework.setHomeworkImageUrls(cdnImageUrls);
        }
        return R.ok(homework);
    }

    @Override
    public R<Object> correct(
            String corpUid, String storeUid, String staffUid, String staffName, String uid,
            Integer status, Integer teacherScore, String evaluationText, Staff staff, StaffRoles staffRole
    ) {
        QueryCondition condition = QueryCondition.createEmpty()
                .and(table.agencyUid.eq(corpUid))
                .and(table.storeUid.eq(storeUid))
                .and(table.uid.eq(uid));

        MstXcxStudentHomework xcxStudentHomework = getMapper().selectOneByCondition(condition);
        if (xcxStudentHomework == null)
            return R.fail("作业不存在！");
        if (xcxStudentHomework.getEnabled().equals(0))
            return R.fail("请批改学生的新课后作业！");
        if (!AccountUtil.isStoreManager(staffRole.getRoles())) {
            if (xcxStudentHomework.getEvaluationStaffUid() != null && staff.getUid() != null &&
                    !xcxStudentHomework.getEvaluationStaffUid().equals(staff.getUid()))
                return R.fail("该学生作业只能由原主讲导读进行批改！");
        }

        Date submissionTime = xcxStudentHomework.getSubmissionTime();
        LocalDateTime submissionDateTime = submissionTime.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();

        LocalDateTime nowDateTime = LocalDateTime.now();
        if (AccountUtil.isStoreManager(staffRole.getRoles())) {
            // 计算1年后的截止日期
            LocalDateTime deadline = submissionDateTime.plusYears(1);
            // 如果当前时间在截止日期之后，则禁止修改
            if (nowDateTime.isAfter(deadline)) {
                return R.fail("操作失败：作业提交已超过1年，无法修改。");
            }
        } else {
            // 计算30天后的截止日期
            LocalDateTime deadline = submissionDateTime.plusDays(30);
            // 如果当前时间在截止日期之后，则禁止修改
            if (nowDateTime.isAfter(deadline)) {
                return R.fail("操作失败：作业提交已超过30天，无法修改。");
            }
        }
        xcxStudentHomework.setStatus(status);
        xcxStudentHomework.setTeacherScore(teacherScore);
        xcxStudentHomework.setEvaluationText(evaluationText);
        xcxStudentHomework.setEvaluationTime(DateUtil.getNowDatetime());
        xcxStudentHomework.setEvaluationStaffUid(NepUtil.nullToZero(staffUid));
        xcxStudentHomework.setLastStaffUid(NepUtil.nullToZero(staffUid));
        xcxStudentHomework.setLastStaffName(NepUtil.nullToZero(staffName));

        boolean b = updateById(xcxStudentHomework);
        return b ? R.ok() : R.fail("批改失败！");
    }
}
